package com.tos.second.interceptor;

import com.tos.second.common.constant.JwtClaimsConstant;
import com.tos.second.properties.JwtProperties;
import com.tos.second.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

@Slf4j
@Component
public class ChatHandshakeInterceptor implements HandshakeInterceptor {
    
    @Autowired
    private JwtProperties jwtProperties;
    
    /**
     * 在握手之前执行，用于身份验证等操作
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, 
                                  WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            String token = servletRequest.getServletRequest().getParameter("token");
            
            if (token != null && !token.isEmpty()) {
                try {
                    // 解析JWT token
                    Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
                    Long userId = Long.valueOf(claims.get(JwtClaimsConstant.ID).toString());
                    
                    // 将用户ID存储到attributes中，供后续使用
                    attributes.put("userId", userId);
                    log.info("用户 {} 通过WebSocket握手验证", userId);
                    return true;
                } catch (Exception e) {
                    log.error("WebSocket握手验证失败: {}", e.getMessage());
                }
            }
        }
        return false; // 验证失败，拒绝连接
    }
    
    /**
     * 握手之后执行
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, 
                              WebSocketHandler wsHandler, Exception exception) {
        // 握手后处理逻辑（如果需要）
        if (exception != null) {
            log.error("WebSocket握手后发生异常: {}", exception.getMessage());
        }
    }
}